package com.hltx.controller.recharge;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.hltx.constants.CommonConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.recharge.RechargeInfo;
import com.hltx.pojo.recharge.RechargeInfoAlipay;
import com.hltx.pojo.user.User;
import com.hltx.resolver.DefiniteException;
import com.hltx.service.alipay.AlipayConfigs;
import com.hltx.service.recharge.AlipayRechargeManager;
import com.hltx.service.recharge.RechargeManager;
import com.hltx.util.ResultInfo;
import com.hltx.util.ResultUtil;

/**
 * 确认充值支付controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/recharge")
public class RechargeHandelController extends BaseController{

	@Autowired
	private RechargeManager rechargeService;
	
	@Autowired
	private AlipayRechargeManager alipayRechargeService;

	

	
	/**
	 * 支付宝手机网站支付
	 * @param pi
	 * @param request
	 * @param session
	 * @param response
	 */
	@RequestMapping(value = "/confirm_alipay_recharge", method = { RequestMethod.POST, RequestMethod.GET })
	public void alipayWapPay(RechargeInfo ri,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response){
		String price=request.getParameter("price");
		User user = (User) session.getAttribute("sessionUser");
		try{
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("price", price);
		if(null==user){
			return ;
		}
		params.put("userId", user.getId());
		Map<String, Object> resMap = rechargeService.saveAliPayRecharge(params);
		
		@SuppressWarnings("unchecked")
		Map<String, String> alipayParams = (Map<String, String>)resMap.get("alipayParams");
		
		if(alipayParams != null){
			String contextPath = request.getContextPath(); 
			String url = alipayRechargeService.alipayWap(alipayParams, contextPath);
			if(StringUtils.isNotEmpty(url)){
				response.setContentType("text/html;charset=" + AlipayConfigs.charSet);
				response.getWriter().write(url);
				response.getWriter().flush();
			}
		}
		
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value="/aliPayReturn")
	public String aliPayReturn(HttpServletRequest request,
			HttpServletResponse response){
		 Map<String, String> map = new HashMap<String, String>();
		 try {
		 @SuppressWarnings("unchecked")
		Map<String, String[]> params = request.getParameterMap();
         for (Entry<String, String[]> entry : params.entrySet()) {
             if (entry.getValue() != null && entry.getValue().length == 1) {
                 map.put(entry.getKey(), entry.getValue()[0]);
             }
         }
         @SuppressWarnings("unused")
		RechargeInfoAlipay result = alipayRechargeService.getReturnResult(map);
         return "redirect:/user";
		 }catch(AlipayApiException e){
			 throw new DefiniteException(e.getMessage()); 
		 }
		 
		 
	}
	
	/**
	 * 微信JS充值
	 * 
	 * @return
	 */
	@RequestMapping(value = "/confirm_wxjs_recharge", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getWxJsApiCode(RechargeInfo ri,HttpServletRequest request, HttpSession session, 
			HttpServletResponse response) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		String price=request.getParameter("price");
		User user = (User) session.getAttribute(
				"sessionUser");
		try{
			if(null==user){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "NO_LOGIN", "用户未登录！"));
				return resMap;
			}
			String openId = (String)session.getAttribute(CommonConstant.OPEN_KEY);
			if(StringUtils.isEmpty(openId)){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "OPENID_NULL", "请使用微信打开商城"));
				return resMap;
			}
				//微信充值			
				Map<String,Object> params = new HashMap<String, Object>();
				params.put("openId", openId);
				params.put("price", price);
				params.put("userId", user.getId());
				params.put("contextPath", request.getContextPath());
				Map<String, Object> saveRes = rechargeService.saveWxPayRecharge(params);
				resMap.put("prePayInfo", saveRes.get("prePayInfo"));
				ResultInfo resultInfo=(ResultInfo)saveRes.get("result");
				if(ResultInfo.SUCCESS.equals(resultInfo.getState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "充值成功"));
				}else{
			     resMap.put("result", this.initResult(ResultInfo.ERROR, "fail", "充值失败"));
				}
			
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统繁忙"));

		}
		return resMap;
	}
	
	
	
	
}
